#!/usr/bin/env bash

# WSL init

_sudo(){
  command -v sudo > /dev/null && echo "sudo" || true
}

set -x

$(_sudo) sed -i "s#deb.debian.org#mirrors.aliyun.com#g" /etc/apt/sources.list
$(_sudo) sed -i "s#security.debian.org#mirrors.aliyun.com#g" /etc/apt/sources.list

$(_sudo) sed -i "s#archive.ubuntu.com#mirrors.aliyun.com#g" /etc/apt/sources.list
$(_sudo) sed -i "s#security.ubuntu.com#mirrors.aliyun.com#g" /etc/apt/sources.list

source ~/.bashrc

if [ -z "$APP_ENV" ];then echo "export APP_ENV=wsl" >> ~/.bashrc; fi

if [ -z "$WSL_HOME" ];then echo "export WSL_HOME=/mnt/c/Users/90621" >> ~/.bashrc; fi

if [ -z "$COMPOSER_HOME" ];then echo "export COMPOSER_HOME=/tmp/composer" >> ~/.bashrc; fi

if [ -z "$DOCKER_BUILDKIT" ];then echo "export DOCKER_BUILDKIT=1" >> ~/.bashrc; fi

if [ -z "$DOCKER_CLI_EXPERIMENTAL" ];then echo "export DOCKER_CLI_EXPERIMENTAL=enabled" >> ~/.bashrc; fi

if [ -z "$DOCKER_HOST" ];then
  # echo "export DOCKER_HOST=127.0.0.1:2375" >> ~/.bashrc
  true
fi

# WSL2
if [ -f /usr/share/docker-desktop/default/cli/bin/docker ];then

  if [ -z "$WSL2_WINDOWS_HOST" ];then
    echo "export WSL2_WINDOWS_HOST=\$(cat /etc/resolv.conf | grep nameserver | awk '{print \$2}' | head -1)" >> ~/.bashrc;
  fi

  if [ -z "$WINDOWS_DOCKER_HOST" ];then
    echo "export WINDOWS_DOCKER_HOST=\${WSL2_WINDOWS_HOST}:2376" >> ~/.bashrc
  fi

  if [ -n "$DOCKER_HOST" ];then
    sed -i "s#^export DOCKER_HOST=.*##g" ~/.bashrc
  fi

fi

$(_sudo) apt update && $(_sudo) apt -y install \
                            bash-completion \
                            vim \
                            git \
                            curl \
                            wget \
                            lsb-release \
                            python3 \
                            python3-pip \
                            openssh-server \
                            apt-file \
                            man \
                            dnsutils

# composer cn mirror

command -v /usr/local/bin/composer \
  && composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ || true

# 命令行补全

if ! [ -d /etc/bash_completion.d ];then $(_sudo) mkdir -p /etc/bash_completion.d; fi

if ! [ -f /etc/bash_completion.d/docker ];then
$(_sudo) curl -L \
  https://raw.githubusercontent.com/docker/docker-ce/master/components/cli/contrib/completion/bash/docker \
  -o /etc/bash_completion.d/docker
fi

# verify
source ~/.bashrc
command -v docker && docker version || true

# cp docker desktop k8s config

mkdir -p ${HOME}/.kube

for user in `ls /mnt/c/Users`;
do
  if [ -f "/mnt/c/Users/${user}/.kube/config" ];then
    if ! [ -f "${HOME}/.kube/config" ];then
      cp "/mnt/c/Users/${user}/.kube/config" ${HOME}/.kube/config

      echo -e "\n\n==> copy .kube folder success\n\n"

      command -v kubectl && kubectl version || true
    fi
  fi
done

echo -e '\n';
